package com.topisv.tms.web.phone;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.costants.Constants;
import com.topisv.tms.costants.Constants.Phone;
import com.topisv.tms.costants.StorageConstants;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.lpn.Pallet;
import com.topisv.tms.entity.lpn.StorageOrder;
import com.topisv.tms.entity.phone.pick.PhonePickTask;
import com.topisv.tms.entity.phone.pick.PhoneWorkTask;
import com.topisv.tms.entity.phone.pick.PhoneWorkTaskItem;
import com.topisv.tms.entity.phone.pkg.PhonePkgCheck;
import com.topisv.tms.entity.pickCar.PickCar;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.lightShelf.LightShelfService;
import com.topisv.tms.service.lpn.PalletService;
import com.topisv.tms.service.lpn.StorageOrderService;
import com.topisv.tms.service.pickCar.PickCarService;
import com.topisv.tms.service.vo.EdiOrderItemVo;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.CopyPropertiesUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/phone")
public class WMSPhoneController {

	private static final Logger log = LoggerFactory.getLogger(WMSPhoneController.class);

	@Autowired
	private WorkTaskService workTaskService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private WorkTaskItemService workTaskItemService;

	@Autowired
	private WorkOrderService workOrderService;

	@Autowired
	private LightShelfService lightShelfService;

	@Autowired
	private PickCarService pickCarService;

	@Autowired
	private CustomersService customersService;

	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;

	@Autowired
	private PalletService palletService;

	@Autowired
	private StorageOrderService storageOrderService;

	// ////////////////////////////////////////////////////////
	// 拣货接口///////////////////////////////////////////////////////////////////////

	/**
	 * 查询待拣货任务列表
	 * 
	 * @param jobuuid
	 *            用户UUID
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxPickTaskList")
	public void ajaxPickTaskList(
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

			// 查找我的拣货任务
			Map<String, Object> param_my = new HashMap<String, Object>();
			User curUser = this.accountService.findUserByJobuuid(jobuuid);
			param_my.put("pickerId", curUser.getId());
			param_my.put("status", "2"); // 任务状态( 1.创建任务 2.已分配拣货任务 3.已拣货 4.
											// 已分配灯光拣选任务 5.已经灯光拣选 6.已分配包装任务
											// 7.已包装 8.已分配发货任务
											// 9.已发货 10.灯光拣选进行中.. 11.推车拣选进行中..)
			List<WorkTask> taskList = this.workTaskService
					.loadTaskByParam(param_my);
			
			List<PhonePickTask> phonePickList = CopyPropertiesUtils.ListToTargetList(taskList, PhonePickTask.class);
			
			json.put("status", "1"); // 查询成功
			json.put("content", phonePickList); // 任务列表

		} catch (Exception e) {

			log.error("jobuuid= " + jobuuid + " error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 查询未分配拣货任务
	 * 
	 * @param jobuuid
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxUnPickTaskList")
	public void ajaxUnPickTaskList(
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			User curUser = this.accountService.findUserByJobuuid(jobuuid);
			if (null != curUser) {
				// 查询未分配的拣货任务
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("areagroups", StringUtils.isBlank(curUser
						.getAreagroups()) ? "blank" : curUser.getAreagroups());
				String customerCodes = this.customersService
						.loadCustomerByAuthority(jobuuid);
				param.put("customerCodes",
						StringUtils.isBlank(customerCodes) ? "blank"
								: customerCodes);
				param.put("status", "1");
				List<WorkTask> untakedPickTaskList = this.workTaskService
						.loadTaskByParam(param);
                List<PhonePickTask>  unPhoneTakedPickTaskList = CopyPropertiesUtils.ListToTargetList(untakedPickTaskList, PhonePickTask.class);
				json.put("status", "1"); // 查询成功
				json.put("content", unPhoneTakedPickTaskList); // 任务列表
			} else {
				log.error("unfound user【" + jobuuid + "】");
				json.put("status", "0");
				json.put("content", "用户不存在或者未登录");
			}
		} catch (Exception e) {

			log.error("jobuuid = " + jobuuid + " error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 根据运单号查找拣货任务
	 * 
	 * @author libin
	 * @param jobuuid
	 * @param expressno
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxPickTaskByExpressNo")
	public void ajaxPickTaskByExpressNo(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "expressno") String expressno,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			User curUser = this.accountService.findUserByJobuuid(jobuuid);
			List<WorkTask> workTasks = new ArrayList<WorkTask>();
			if (null != curUser) {
				WorkTask untakedPickTask = null;
				untakedPickTask = this.workTaskService
						.loadTaskByCode(expressno);
				if (null != untakedPickTask) { // 扫描任务号
					workTasks.add(untakedPickTask);
					List<PhonePickTask> phonePickTask = CopyPropertiesUtils.ListToTargetList(workTasks, PhonePickTask.class);
					log.info("任务号：" + expressno);
					json.put("status", "1");
					json.put("content", phonePickTask);
				} else { 
					json.put("status", "0");
					json.put("content", "未找到对应任务");
				}
			}
		} catch (Exception e) {
			log.error("jobuuid = " + jobuuid + " error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 拣货绑定流转箱
	 * 
	 * @param workBoxCode
	 *            流转箱编码
	 * @param taskCode
	 *            任务编号
	 * @param jobuuid
	 *            工号
	 * @param response
	 */
	@RequestMapping(value = "ajaxBindBox")
	public void ajaxBindBox(
			@RequestParam(value = "workBoxCode") String workBoxCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "jobuuid", required = false) String jobuuid,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			String msg = this.workTaskService.bindBox_app(workBoxCode,
					taskCode, jobuuid);

			if ("fast".equals(msg)) {
                json.put("status", "0");
                json.put("content", "已被快捷领取！");
            } else if ("token".equals(msg)) {
				json.put("status", "0");
				json.put("content", "任务已经被领取！");
			} else if ("tokenByself".equals(msg)) {
				json.put("status", "2");
				json.put("content", "任务被自己领取！");
			} else if ("busy".equals(msg)) {
				json.put("status", "0");
				json.put("content", "流转箱被占用！");
			} else if ("error".equals(msg)) {
				json.put("status", "0");
				json.put("content", "流转箱条码异常!");
			} else if ("success".equals(msg)) {
				json.put("status", "1");
				json.put("content", "绑定成功,请开始拣货!");
			}

		} catch (Exception e) {
			log.error("workBoxCode = " + workBoxCode + " taskCode=" + taskCode
					+ " jobuuid=" + jobuuid + " error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常!");
		}
		out.print(json.toString());
	}

	@RequestMapping(value = "ajaxBindBox2")
	public void ajaxBindBox2(
			@RequestParam(value = "workBoxCode") String workBoxCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "jobuuid", required = false) String jobuuid,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			String msg = this.workTaskService.bindBox_app2(workBoxCode,
					taskCode, jobuuid);
			if ("fast".equals(msg)) {
                json.put("status", "0");
                json.put("content", "已被快捷领取！");
            } else if ("token".equals(msg)) {
				json.put("status", "0");
				json.put("content", "任务已经被领取！");
			} else if ("tokenByself".equals(msg)) {
				json.put("status", "2");
				json.put("content", "任务被自己领取！");
			} else if ("busy".equals(msg)) {
				json.put("status", "0");
				json.put("content", "流转箱被占用！");
			} else if ("error".equals(msg)) {
				json.put("status", "0");
				json.put("content", "流转箱条码异常!");
			} else if ("success".equals(msg)) {
				json.put("status", "1");
				json.put("content", "绑定成功,请开始拣货!");
			}

		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常!");
		}
		out.print(json.toString());
	}

	/**
	 * 查询拣货任务项
	 * 
	 * @param taskCode
	 *            任务编码
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickTaskDetail")
	public void ajaxPickTaskDetail(
			@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

			WorkTaskItem workTaskItem = workTaskItemService
					.findByTaskCodeAndRankno(taskCode, 1);
			if (null != workTaskItem) {
				int rankno = workTaskItem.getRankno();

				while ("picked".equals(workTaskItem.getPickStatus())) {
					++rankno;
					workTaskItem = workTaskItemService.findByTaskCodeAndRankno(
							workTaskItem.getTaskCode(), rankno);
				}

				if ("picked".equals(workTaskItem.getPickStatus())) {
					json.put("status", "0");
					json.put("content", "数据有误");
				} else {
					json.put("status", "1");
					json.put("content", "查询成功");

					WorkTask task = this.workTaskService
							.loadTaskByCode(workTaskItem.getTaskCode());
					PhoneWorkTask phoneWorkTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(task, PhoneWorkTask.class);
                    PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);

                    json.put("taskItem", phoneWorkTaskItem);
                    json.put("task", phoneWorkTask);
				}
			} else {

			}
		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 查询拣货任务项
	 * 
	 * @param taskCode
	 *            任务编码
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxListTaskDetail")
	public void ajaxListTaskDetail(
			@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			WorkTask task = this.workTaskService.loadTaskByCode(taskCode);
			List<WorkTaskItem> workTaskItems = workTaskItemService
					.loadByTaskCode(taskCode);
			if (null != workTaskItems) {
				for (WorkTaskItem eOI : workTaskItems) {
					EdiGoodsSku eGS = ediGoodsSkuService
							.findByCustomerCodeAndSku(task.getCustomerCode(),
									eOI.getSku());
					if (eGS == null) {
						continue;
					}
					eOI.setSkuName(eGS.getSkuName());
				}
				json.put("status", "1");
				json.put("content", "查询成功");
				
				List<PhoneWorkTaskItem> phoneWorkTaskItems = CopyPropertiesUtils.ListToTargetList(workTaskItems, PhoneWorkTaskItem.class);
                PhoneWorkTask phoneWorkTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(task, PhoneWorkTask.class);
				
				json.put("taskItems", phoneWorkTaskItems);

				json.put("task", phoneWorkTask);

			}
		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 拣货
	 * 
	 * @param taskItemId
	 *            拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxPick")
	public void ajaxPick(@RequestParam(value = "taskItemId") Long taskItemId,
			String sku, @RequestParam(value = "num", required = false) int num,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			/** begin add bug:360. 防止重复操作的校验. 20160621, lianghe.yuan */
			isLockSuccess = workTaskService.lock("ajaxPick", taskItemId + "", "-");
			
			if (!isLockSuccess) {
			    json.put("status", "0");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			/** end add bug:360. 防止重复操作的校验. 20160621, lianghe.yuan */

			// 拣货
			String msg = this.workTaskService.pick(taskItemId, sku, num);
			WorkTaskItem workTaskItem = workTaskItemService.findOne(taskItemId);
			int rankno = workTaskItem.getRankno();
			if ("error".equals(msg)) {
				json.put("status", "0");
				json.put("content", "验证不通过");
			} else if ("finished".equals(msg)) {
				json.put("status", "0");
				json.put("content", "此任务项已完成");
			} else if ("task_finished".equals(msg)) {
				json.put("status", "0");
				json.put("content", "此任务已完成");
			} else if ("coutinue".equals(msg)) {
				json.put("status", "1");
				json.put("content", "拣货成功,继续此任务项拣货 ");

				WorkTask task = this.workTaskService
						.loadTaskByCode(workTaskItem.getTaskCode());
				
				PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
                PhoneWorkTask phoneWorkTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(task, PhoneWorkTask.class);

                json.put("taskItem", phoneWorkTaskItem);
				json.put("task", phoneWorkTask);
			} else if ("finishing".equals(msg)) {
				json.put("status", "2");
				json.put("content", "拣货成功,此任务项完成  ");

				workTaskItem = workTaskItemService.findByTaskCodeAndRankno(
						workTaskItem.getTaskCode(), ++rankno);			

				WorkTask task = this.workTaskService
						.loadTaskByCode(workTaskItem.getTaskCode());
				
				PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
                PhoneWorkTask phoneWorkTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(task, PhoneWorkTask.class);
                
                json.put("taskItem", phoneWorkTaskItem);
				json.put("task", phoneWorkTask);
			} else if ("task_finishing".equals(msg)) {
				json.put("status", "3");
				json.put("content", "拣货成功,此任务已经完成 ");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally {
			if (isLockSuccess) {
		        // add bug:360. 防止重复操作的校验. 操作完成，释放锁. 20160621, lianghe.yuan
		        workTaskService.releaseLock("ajaxPick", taskItemId + "");
		    }
		}
		out.print(json.toString());
	}

	/**
	 * 拣货_优化 by ch 20140402
	 * 
	 * @param taskItemId
	 *            拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxPick_1")
	public void ajaxPick_1(@RequestParam(value = "taskItemId") Long taskItemId,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "boxCode") String boxCode,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();

			isLockSuccess = workTaskService.lock("ajaxPick_1", taskItemId + "", "-");
			
			if (!isLockSuccess) {
			    json.put("status", "0");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			
			// 拣货
			String msg = this.workTaskService.pick(taskItemId, sku, boxCode);
			WorkTaskItem workTaskItem = workTaskItemService.findOne(taskItemId);
			int rankno = workTaskItem.getRankno();
			if ("error_itemnull".equals(msg)) {
				json.put("status", "1");
				json.put("content", "无此任务项");
			} else if ("error_sku".equals(msg)) {
				json.put("status", "2");
				json.put("content", "sku码错误");
			} else if ("error_boxCode".equals(msg)) {
				json.put("status", "3");
				json.put("content", "库位箱编码错误");
			} else if ("error_finished".equals(msg)) {
				json.put("status", "4");
				json.put("content", "此任务项已经完成");
			} else if ("item_finishing".equals(msg)) {
				json.put("status", "5");
				json.put("content", "拣货成功,继续下一个任务项");

				PhoneWorkTaskItem phoneWorkTaskItem = null;
				PhoneWorkTask phoneWorkTask = null;
				WorkTask task = null;
				
				workTaskItem = workTaskItemService.findByTaskCodeAndRankno(workTaskItem.getTaskCode(), ++rankno);
				
				if(workTaskItem != null){
	                task = this.workTaskService.loadTaskByCode(workTaskItem.getTaskCode());
	                phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
	                phoneWorkTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(task, PhoneWorkTask.class);
				}
				
                json.put("taskItem", phoneWorkTaskItem);
                json.put("task", phoneWorkTask);
			} else if ("task_finishing".equals(msg)) {
				json.put("status", "6");
				json.put("content", "拣货成功,此任务已经完成 ");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally {
			if (isLockSuccess) {
		        // add bug:360. 防止重复操作的校验. 操作完成，释放锁. 20160621, lianghe.yuan
		        workTaskService.releaseLock("ajaxPick_1", taskItemId + "");
		    }
		}
		out.print(json.toString());
	}

	/**
	 * 任务绑定推车
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxBindCar")
	public void ajaxBindCar(@RequestParam(value = "carCode") String carCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "jobuuid", required = false) String jobuuid,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			String msg = this.pickCarService
					.bindCar(carCode, taskCode, jobuuid); // 任务绑定推车
			
			if ("fast".equals(msg)) {
                json.put("status", "0");
                json.put("content", "已被快捷领取！");
            } else if ("busy".equals(msg)) {
				json.put("status", "0");
				json.put("content", "推车被占用");
			} else if ("continue".equals(msg)) {
				json.put("status", "2"); // 继续任务
				json.put("content", "继续任务");
			} else if ("unfixed".equals(msg)) {
				json.put("status", "3"); // 推车编码和任务不匹配
				json.put("content", "推车编码和任务不匹配");
			} else if ("less".equals(msg)) {
				json.put("status", "4"); // 车位不够
				json.put("content", "车位不够");
			} else if ("success".equals(msg)) {
				json.put("status", "1"); // 成功绑定
				json.put("content", "成功绑定");
			} else if ("noexist".equals(msg)) {
				json.put("status", "5"); // 成功绑定
				json.put("content", "系统中没有此推车编码，请登记或者换个正确编码");
			}
			log.info("Task[" + taskCode + "] bind car [" + carCode
					+ "] ret = [" + msg + "]");

		} catch (Exception e) {

			log.error("Task[" + taskCode + "] bind car [" + carCode + "] ", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 推车拣选
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxPickAndSetGooods")
	public void ajaxPickAndSetGooods(
			@RequestParam(value = "carCode") String carCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "taskItemId") Long taskItemId,
			@RequestParam(value = "num", required = false) Integer num,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		
		boolean isLockSuccess = false;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			/** begin add bug:360. 防止重复操作的校验. 20160621, lianghe.yuan */
			isLockSuccess = workTaskService.lock("ajaxPickAndSetGooods", taskCode, "-");
			
			if (!isLockSuccess) {
			    json.put("status", "0");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			/** end add bug:360. 防止重复操作的校验. 20160621, lianghe.yuan */

			if (null == num || num == 0)
				num = 1;
			String msg = this.workTaskService.pick(taskItemId, sku, num); // 拣货
			PickCar car = this.pickCarService.loadCarByCode(carCode);
			WorkTask task = this.workTaskService.loadTaskByCode(taskCode);
			WorkTaskItem workTaskItem = workTaskItemService.findOne(taskItemId);
			int rankNo = workTaskItem.getRankno();
			log.info("msg = " + msg);
			json.put("msg", msg);

			if (msg.equals("continue")) {
				Map<String, String> result = null;
				for (int i = 0; i < num; i++) {
					result = this.pickCarService.setGoods(car.getId(), sku,
							task.getId()); // 上架
				}
				json.put("status", "1");
				json.put("content", (String) result.get("stockCode")); // 返回拣选车位


				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
				PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
                PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
                
                json.put("taskItem", phoneWorkTaskItem);
				json.put("task", _phoneTask);
			} else if (msg.equals("finishing")) {
				Map<String, String> result = null;
				for (int i = 0; i < num; i++) {
					result = this.pickCarService.setGoods(car.getId(), sku,
							task.getId()); // 上架
				}
				json.put("status", "2");// 任务项完成
				json.put("content", (String) result.get("stockCode")); // 返回拣选车位

				// workTaskItem=workTaskItemService.findByTaskCodeAndRankno(workTaskItem.getTaskCode(),
				// ++rankNo);
				List<WorkTaskItem> items = workTaskItemService
						.findUncompletedTaskItemBy(workTaskItem.getTaskCode());
				if (null != items && items.size() > 0) {
					workTaskItem = items.get(0);
					PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);                                
					json.put("taskItem", phoneWorkTaskItem);
				}
				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
				PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
				json.put("task", _phoneTask);
			} else if (msg.equals("task_finishing")) {
				Map<String, String> result = null;
				for (int i = 0; i < num; i++) {
					result = this.pickCarService.setGoods(car.getId(), sku,
							task.getId()); // 上架
				}
				json.put("status", "3");// 任务完成
				json.put("content", (String) result.get("stockCode")); // 返回拣选车位

				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
				PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
				json.put("task", _phoneTask);
			} else if (msg.equals("finished")) {
				json.put("status", "4");
				json.put("content", "已经拣过的任务项");
			} else {
				json.put("status", "0");
				json.put("content", "验证不通过");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally {
			if (isLockSuccess) {
		        // add bug:360. 防止重复操作的校验. 操作完成，释放锁. 20160621, lianghe.yuan
		        workTaskService.releaseLock("ajaxPickAndSetGooods", taskCode);
		    }
		}
		out.print(json.toString());
	}
	/**
	 * 推车拣选 筐位指引模式
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxPickByCarAndBasket")
	public void ajaxPickByCarAndBasket(
			@RequestParam(value = "carCode") String carCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "taskItemId") Long taskItemId,
			@RequestParam(value = "num", required = false) Integer num,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		Integer pickNum=0;//当前筐位需要的sku个数
		Integer limitNum=0;//update CaStockSkuStatus 的个数,真实拣货个数
		String msg ="";
		boolean isLockSuccess = false;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			/** begin add bug:357. 防止重复操作的校验. 20160618, lianghe.yuan */
			isLockSuccess = workTaskService.lock("ajaxPickByCarAndBasket", taskCode, "-");
			
			if (!isLockSuccess) {
			    json.put("status", "0");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			/** end add bug:357. 防止重复操作的校验. 20160618, lianghe.yuan */
			
			//查询当前扫描sku的数量和筐位
			Map<String,Object> resultMap= pickCarService.loadCarStock(taskCode,carCode,sku);
			if (resultMap == null || resultMap.size()<1) {
				json.put("status", "0");
	            json.put("content", "推车筐位异常！");
	            out.print(json.toString());
	            return;
			}
			pickNum=Integer.parseInt(resultMap.get("num").toString());
			PickCar car = this.pickCarService.loadCarByCode(carCode);
			WorkTask task = this.workTaskService.loadTaskByCode(taskCode);
			WorkTaskItem workTaskItem = workTaskItemService.findOne(taskItemId);
			
			limitNum=getPickNum(pickNum,workTaskItem.getNum().intValue()-workTaskItem.getPickedNum().intValue());//比较当前筐位需要的数量和当前库位上的数量，返回较小的值
			msg=this.workTaskService.pick(taskItemId, sku,limitNum);
			log.info("msg = " + msg+"-----------sku:"+sku+"-->拣货数量limitNum:"+limitNum);
			json.put("msg", msg);

			if (msg.equals("continue")) {
				String msg1= pickCarService.setGoodsNew(car.getId(),task.getId(),resultMap.get("stock_id").toString(),sku,limitNum);
				log.info("msg1="+msg1);
				json.put("status", "1");
				json.put("content", "放"+(String) resultMap.get("stock_code")+"位," +limitNum +"件"); // 返回拣选车位
				
				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
				PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
                PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
                
                json.put("taskItem", phoneWorkTaskItem);
				json.put("task", _phoneTask);
			} else if (msg.equals("finishing")) {
				String msg1= pickCarService.setGoodsNew(car.getId(),task.getId(),resultMap.get("stock_id").toString(),sku,limitNum);
				log.info("msg1="+msg1);
				json.put("status", "2");// 任务项完成
				json.put("content", "放"+(String) resultMap.get("stock_code")+"位," +limitNum+"件"); // 返回拣选车位
				List<WorkTaskItem> items = workTaskItemService
						.findUncompletedTaskItemBy(workTaskItem.getTaskCode());
				if (null != items && items.size() > 0) {
					workTaskItem = items.get(0);
					PhoneWorkTaskItem phoneWorkTaskItem = (PhoneWorkTaskItem) CopyPropertiesUtils.ObjectToTargetObject(workTaskItem, PhoneWorkTaskItem.class);
					json.put("taskItem", phoneWorkTaskItem);
				}
				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
				PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
                
				json.put("task", _phoneTask);
			} else if (msg.equals("task_finishing")) {
				String msg1= pickCarService.setGoodsNew(car.getId(),task.getId(),resultMap.get("stock_id").toString(),sku,limitNum);
				log.info("msg1="+msg1);
				json.put("status", "3");// 任务完成
				json.put("content", "放"+(String) resultMap.get("stock_code")+"位," + limitNum+"件"); // 返回拣选车位

				WorkTask _task = this.workTaskService.loadTaskByCode(taskCode);
			    PhoneWorkTask _phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(_task, PhoneWorkTask.class);
	            
				json.put("task", _phoneTask);
			} else if (msg.equals("finished")) {
				json.put("status", "4");
				json.put("content", "已经拣过的任务项");
			} else {
				json.put("status", "0");
				json.put("content", "验证不通过");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		} finally {
		    if (isLockSuccess) {
		        // add bug:357. 防止重复操作的校验. 操作完成，释放锁. 20160618, lianghe.yuan
		        workTaskService.releaseLock("ajaxPickByCarAndBasket", taskCode);
		    }
		}
		out.print(json.toString());
	}
	
	/**
	 * 返回较小的值
	 * @param pickNum
	 * @param num
	 * @return
	 */
	private Integer getPickNum(Integer pickNum, Integer num) {
		return pickNum>num?num:pickNum;
	}
	// ////////////////////////////////////////////////////////
	// 包装接口///////////////////////////////////////////////////////////////////////

	/**
	 * 包装验证 （根据运单号、订单号）
	 * 
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxPkgCheck")
	public void ajaxPkgCheck(
			@RequestParam(value = "expressNo") String expressNo,
			@RequestParam(value = "orderno") String orderno,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

			WorkOrder workOrder = this.workOrderService
					.loadByExpressNoAndOrderno(expressNo, orderno);
			if (workOrder == null) {// 验证不成功
				json.put("status", "0");
				json.put("content", "验证不成功！");
			} else {
				String status = workOrder.getStatus();
				if ("5".equals(status) || "6".equals(status)
						|| "7".equals(status)) {
					json.put("status", "1");
					json.put("content", "567");
				} else {

					// 验证成功
					json.put("status", "1");

					List<EdiOrderItem> items = workOrder.getOrder()
							.getOrderItems();
					List<EdiOrderItemVo> temp = new ArrayList<EdiOrderItemVo>();
					Map<String, Integer> map = new HashMap<String, Integer>();
					for (EdiOrderItem item : items) {
						String sku = item.getSku();
						Integer qty = item.getQty();
						if (map.containsKey(sku)) {
							map.put(sku, map.get(sku) + qty);
						} else {
							map.put(sku, qty);
						}
					}
					for (Map.Entry<String, Integer> m : map.entrySet()) {
						String sku = m.getKey();
						Integer qty = m.getValue();
						EdiOrderItemVo vo = new EdiOrderItemVo();
						vo.setSku(sku);
						vo.setQty(qty);
						temp.add(vo);
					}
					
					List<PhonePkgCheck> phoneTemp = CopyPropertiesUtils.ListToTargetList(temp, PhonePkgCheck.class);
					json.put("content", phoneTemp);
				}
			}

		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * ajax根据任务号号查询待包装的订单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCheckTaskCode")
	public void ajaxCheckTaskCode(ServletRequest request,
			HttpServletResponse response) {

		PrintWriter out = null;
		JSONObject json = null;
		String msg = null;
		try {

			out = response.getWriter();
			json = new JSONObject();

			String taskCode = request.getParameter("taskCode");
			WorkTask workTask = this.workTaskService.loadTaskByCode(taskCode);
			if (workTask == null) { // 无匹配的任务号
				msg = "error";
			} else if ("promotion".equals(workTask.getTacticsType())
					|| "comb".equals(workTask.getTacticsType())) { // 取消单
				if ("7".equals(workTask.getStatus())
						|| "8".equals(workTask.getStatus())
						|| "9".equals(workTask.getStatus())) {
					msg = "status_error";
				} else {
					msg = "success";
					List<WorkTaskItem> taskItems = this.workTaskItemService
							.loadByTaskCode(taskCode);
					
					List<PhoneWorkTaskItem> phoneTaskItems = CopyPropertiesUtils.ListToTargetList(taskItems, PhoneWorkTaskItem.class);
                    PhoneWorkTask phoneTask = (PhoneWorkTask) CopyPropertiesUtils.ObjectToTargetObject(workTask, PhoneWorkTask.class);
                    
					json.put("taskItems", phoneTaskItems);
					json.put("workTask", phoneTask);
				}

			} else {

				msg = "type_error";
			}

			json.put("msg", msg);
			out.print(json);

		} catch (Exception e) {

			log.error("error", e);
			json.put("msg", "error");
			out.print(json);
		}
	}

	/**
	 * 包装
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxPkgBatch")
	public void ajaxPkgBatch(ServletRequest request,
			HttpServletResponse response) {

		PrintWriter out = null;
		JSONObject json = null;
		String msg = null;

		try {

			out = response.getWriter();
			json = new JSONObject();

			// ShiroUser curUser = (ShiroUser)
			// SecurityUtils.getSubject().getPrincipal();

			String taskCode = request.getParameter("taskCode");
			String jobuuid = request.getParameter("jobuuid");
			msg = this.workTaskService.pkgBatch(taskCode, jobuuid);
			json.put("msg", msg);
			out.print(json);

		} catch (Exception e) {
			log.error("error", e);
			json.put("msg", "error");
			out.print(json);
		}
	}

	/**
	 * 包装验证 （根据运单号）
	 * 
	 * @param response
	 */
	@RequestMapping(value = "ajaxPkgCheck_1")
	public void ajaxPkgCheck(
			@RequestParam(value = "expressNo") String expressNo,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		long t1 = System.currentTimeMillis();
		try {
			json = new JSONObject();
			out = response.getWriter();
			if (null != expressNo && !"".equals(expressNo)) {
				WorkOrder workOrder = this.workOrderService
						.loadByExpressNo(expressNo);
				if (workOrder == null) {// 验证不成功
					json.put("status", "0");
					json.put("content", "非本批次运单号");
				} else {
					String status = workOrder.getStatus();
					if ("5".equals(status) || "6".equals(status)
							|| "7".equals(status)) {
						json.put("status", "1");
						json.put("content", "567");
					}else if("cancel".equals(workOrder.getCancelStatus())) {
						json.put("status", "0");
						json.put("content", "此单是取消单");
					}
					else {
						// 验证成功
						json.put("status", "1");
						List<EdiOrderItem> items = workOrder.getOrder()
								.getOrderItems();
						List<EdiOrderItemVo> temp = new ArrayList<EdiOrderItemVo>();
						Map<String, Integer> map = new HashMap<String, Integer>();
						for (EdiOrderItem item : items) {
							String sku = item.getSku();
							Integer qty = item.getQty();
							String sellFlg = item.getSellFlg();
							String key = sellFlg + "_" + sku;
							if (map.containsKey(key)) {
								map.put(key, map.get(key) + qty);
							} else {
								map.put(key, qty);
							}
						}
						for (Map.Entry<String, Integer> m : map.entrySet()) {
							String key = m.getKey();
							Integer qty = m.getValue();
							String sellFlg = key.split("_")[0];
							String sku = key.split("_")[1];
							EdiOrderItemVo vo = new EdiOrderItemVo();
							vo.setSku(sku);
							vo.setQty(qty);
							vo.setSellFlg(sellFlg);
							temp.add(vo);
						}
						json.put("content", temp);
						json.put("ordeno", workOrder.getOrder().getOrdeno());
					}
				}
			} else {
				json.put("status", "0");
				json.put("content", "请输入运单号");
			}
		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
		long t2 = System.currentTimeMillis();
		log.info("app测试--包装验证ajaxPkgCheck--expressNo"+expressNo+"--"+(t2-t1));
	}

	/**
	 * 包装
	 * 
	 * @param orderno
	 *            订单编号
	 * @param jobuuid
	 *            员工uuid
	 * @param response
	 */
	@RequestMapping(value = "ajaxPkg")
	public void ajaxPkg(@RequestParam(value = "orderno") String orderno,
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {
		long t1 = System.currentTimeMillis();
		
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

			String msg = this.workTaskService.pkg(orderno, jobuuid);
			log.info("定单号（" + orderno + "）包装返回： " + msg);
			if (msg.equals("success")) {
				json.put("status", "1"); // 包装成功
				json.put("content", "包装成功");

				/*
				 * try { WorkOrder
				 * workOrder=this.workOrderService.loadOrderByOrderno(orderno);
				 * if("ebill".equals(workOrder.getBillType())){
				 * if("YTO".equals(workOrder.getExpressCompany())){
				 * if(!"create".equals(workOrder.getEbillStatus())){
				 * SynchroShippedBatchQueue
				 * .putSendMessageQueue("createOrdenoYTO"
				 * +StatusEnums.split.getStatus()+
				 * workOrder.getOrder().getOrdeno());//向圆通平台创建电子面单 } } }
				 * 
				 * if(!"finish".equals(workOrder.getSendOutStatus())){
				 * SynchroShippedBatchQueue
				 * .putSendMessageQueue("sendOutOrdeno"+StatusEnums
				 * .split.getStatus()+workOrder. getOrder().getOrdeno()); } }
				 * catch (Exception e) {
				 * 
				 * }
				 */

			} else if (msg.equals("cancel")) {
				json.put("status", "2"); // 取消单
				json.put("content", "取消单,请处理!");
			} else if (msg.equals("pkged")) {
				json.put("status", "3"); // 已包装
				json.put("content", "已包装");
			} else if (msg.equals("error")) {
				json.put("status", "4");
				json.put("content", "不在包装状态!");
			} else if ("unprinted".equals(msg)) {
				json.put("status", "0"); // 异常
				json.put("content", "运单还未打印");
			} else {
				json.put("status", "0"); // 异常
				json.put("content", "包装异常");
			}

		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
		
		long t2 = System.currentTimeMillis();
		log.info("app测试--包装ajaxPkg--orderno"+orderno+"--"+(t2-t1));
	}

	// ////////////////////////////////////////////////////////
	// 发货接口///////////////////////////////////////////////////////////////////////

	/**
	 * 发货_称重
	 * 
	 * @param expressNo
	 *            运单编号(普通运单或电子运单)
	 * @param jobuuid
	 *            员工uuid
	 * @param response
	 */
	@RequestMapping(value = "ajaxSend")
	public void ajaxSend(
			@RequestParam(value = "expressNo") String expressNo,
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "weight", required = false, defaultValue = "0") Integer weight,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		long t1 = System.currentTimeMillis();
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("WMS手机发货开始");
			log.info("快递单号:" + expressNo);
			log.info("重量:" + weight);
			log.info("jobuuid:" + jobuuid);
			if (StringUtils.isBlank(expressNo)) {
				json.put("status", 0);
				json.put("content", "快递单号不能为空");
				out.print(json.toString());
				return;
			}
			User user = accountService.findUserByJobuuid(jobuuid);
			if (user == null) {
				json.put("status", 0);
				json.put("content", "该用户不存在");
				out.print(json.toString());
				return;
			}
			log.info("发货人姓名:" + user.getRealname());
			// 发货
			String msg = this.workOrderService.send(expressNo, jobuuid, weight);
			if (msg.equals("noexist")) {
				json.put("status", "0");
				json.put("content", "不存在此订单!");
			} else if (msg.equals("success")) {
				json.put("status", "1");
				json.put("content", "发货成功!");
				workOrderService.afterOrderSendOut(expressNo);
			} else if (msg.equals("cancel")) {
				json.put("status", "2");
				json.put("content", "取消单,请处理!");
			} else if (msg.equals("fail")) {
				json.put("status", "2");
				json.put("content", "发货失败");
			} else if (msg.equals("sended")) {
				json.put("status", "3");
				json.put("content", "重复发货!");
			} else if (msg.equals("nostatus")) {
				json.put("status", "0");
				json.put("content", "不在发货状态!");
			} else {
				json.put("status", "0");
				json.put("content", "异常!");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		log.info("手机发货结果：" + json.toString());
		out.print(json.toString());
		long t2 = System.currentTimeMillis();
		log.info("app测试--正常发货ajaxSend--expressNo"+expressNo+"--"+(t2-t1));
	}

	/**
	 * 发货_不称重
	 * 
	 * @param expressNo
	 *            运单编号(普通运单或电子运单)
	 * @param jobuuid
	 *            员工uuid
	 * @param multiAllow
	 *            为true，允许多件累加默认总量不称重发货，false，多件要求称重发货
	 * @param response
	 */
	@RequestMapping(value = "ajaxSend_noweight")
	public void ajaxSend_noweight(
			@RequestParam(value = "expressNo") String expressNo,
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "multiAllow", required = false) String multiAllow,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		long t1 = System.currentTimeMillis();
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("WMS手机发货开始");
			log.info("快递单号:" + expressNo);
			log.info("jobuuid:" + jobuuid);
			User user = accountService.findUserByJobuuid(jobuuid);
			if (user == null) {
				json.put("status", 0);
				json.put("content", "该用户不存在");
				out.print(json.toString());
				return;
			}
			log.info("发货人姓名:" + user.getRealname());

			// 发货,multiAllow=true 允许多件累加默认总量不称重发货
			String msg = this.workOrderService.send_noweight(expressNo,
					jobuuid, "true".equals(multiAllow));
			if (msg.equals("noexist")) {
				json.put("status", "0");
				json.put("content", "不存在此订单!");
			} else if (msg.equals("nostatus")) {
				json.put("status", "0");
				json.put("content", "不在发货状态!");
			} else if (msg.equals("success")) {
				json.put("status", "1");
				json.put("content", "发货成功!");
				workOrderService.afterOrderSendOut(expressNo);
			} else if (msg.equals("cancel")) {
				json.put("status", "2");
				json.put("content", "取消单,请处理!");
			} else if (msg.equals("fail")) {
				json.put("status", "2");
				json.put("content", "回传异常,请处理!");
			} else if (msg.equals("sended")) {
				json.put("status", "3");
				json.put("content", "重复发货!");
			} else if (msg.equals("nosetting")) {
				json.put("status", "4");
				json.put("content", "无重量配置，请选择称重发货!");
			} else if (msg.equals("multi")) {
				json.put("status", "5");
				json.put("content", "多件商品，请选择称重发货!");
			} else {
				json.put("status", "0");
				json.put("content", "异常!");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
		long t2 = System.currentTimeMillis();
		log.info("app测试--发货ajaxSend_noweight--expressNo"+expressNo+"--"+(t2-t1));
	}

	// ////////////////////////////////////////////////////////
	// 灯光拣选///////////////////////////////////////////////////////////////////////
	/**
	 * 任务绑定灯光架
	 * 
	 * @param shelfCode
	 *            架编码
	 * @param boxCode
	 *            箱编码
	 * @param jobuuid
	 * @return
	 */
	@RequestMapping(value = "ajaxBindLightShelf")
	public void ajaxBindLightShelf(
			@RequestParam(value = "shelfCode") String shelfCode,
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			// 任务绑定灯光架
			Map<String, String> map = this.lightShelfService.bindLightShelf(
					shelfCode, boxCode, jobuuid);
			String msg = map.get("msg");
			if ("shelfNotFound".equals(msg)) {
				json.put("status", "8");
				json.put("content", "灯光架没有系统登记");
			} else if ("boxNotFound".equals(msg)) {
				json.put("status", "7");
				json.put("content", "拣货箱没有系统登记");
			} else if ("boxNotInTask".equals(msg)) {
				json.put("status", "6");
				json.put("content", "空闲的拣货箱");
			} else if ("taskNotFound".equals(msg)) {
				json.put("status", "5");
				json.put("content", "系统内无拣货箱对应任务信息");
			} else if ("busy".equals(msg)) {
				json.put("status", "4");
				json.put("content", "灯光架已被占用");
			} else if ("less".equals(msg)) {
				json.put("status", "3");
				json.put("content", "灯光架位数不够！");
			} else if ("continue".equals(msg)) {
				json.put("status", "2");
				json.put("content", (String) map.get("taskCode"));
			} else if ("success".equals(msg)) {
				json.put("status", "1");
				json.put("content", (String) map.get("taskCode"));
			} else if ("error".equals(msg)) {
				json.put("status", "0");
				json.put("content", "拣货还未完成");
			}

		} catch (Exception e) {

			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 灯光上架
	 * 
	 * @param shelfCode
	 *            灯光架编码
	 * @param taskCode
	 *            任务编号
	 * @param sku
	 *            sku编码
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxSetGoodsToLigthshelf")
	public void ajaxSetGoodsToLigthshelf(
			@RequestParam(value = "shelfCode") String shelfCode,
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "sku") String sku,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			// 上架
			Map<String, String> result = this.lightShelfService.setGoods(
					shelfCode, sku, taskCode);
			String msg = result.get("msg");

			// 任务已经完成
			if ("hasfinished".equals(msg)) {
				json.put("status", "0");
				json.put("content", "任务已经完成");
			}
			// 验证通过,上架成功
			else if ("success".equals(msg)) {
				String isFinished = result.get("isFinished");
				if ("finished".equals(isFinished)) {
					this.lightShelfService.completeLampPickTask(taskCode);
					json.put("status", "2"); // 上架成功,且任务全部完成
					json.put("content", result.get("stockCode"));// 返回灯光架位
					json.put("stockName", result.get("stockName"));// 返回灯光架位
				} else {
					json.put("status", "1"); // 上架成功
					json.put("content", result.get("stockCode"));// 返回灯光架位
					json.put("stockName", result.get("stockName"));// 返回灯光架位
				}
			}
			// 验证不通过
			else {
				json.put("status", "0");
				json.put("content", "验证不通过");
			}

		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	// ////////////////////////////////////////////////////////
	// 取消订单///////////////////////////////////////////////////////////////////////
	/**
	 * 取消订单
	 * 
	 * @return
	 */
	@RequestMapping(value = "ajaxCancelOrder")
	public void ajaxCancelOrder(
			@RequestParam(value = "orderno") String orderno,
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();

			String msg = this.workOrderService.cancelOrder(orderno, jobuuid);

			if ("success".equals(msg)) {
				json.put("status", "1"); // 成功取消
				json.put("content", "成功取消");
			} else if ("cancel".equals(msg)) {
				json.put("status", "2");
				json.put("content", "已经取消，不能重复取消");
			} else if ("noexist".equals(msg)) {
				json.put("status", "3");
				json.put("content", "不存在此订单");
			} else {
				json.put("status", "4");
				json.put("content", "验证异常");
			}

		} catch (Exception e) {
			log.error("error.", e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}

	/**
	 * 订单复核<br/>
	 * 根据订单号和运单号进行核对.
	 * 
	 * @param expressNo
	 * @param orderno
	 * @param response
	 *            [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @author zhangpeijun
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "ajaxOrderRecheck")
	public void ajaxOrderRecheck(
			@RequestParam(value = "orderno") String orderno,
			@RequestParam(value = "expressNo") String expressNo,
			HttpServletResponse response) {
		/*
		 * TODO 返回值的国际化，返回值的提取,后续根据项目组规划来实现。
		 */
		JSONObject json = getInitJson();
		log.debug("ajaxOrderRecheck Param orderNo=" + orderno + ", expressNo="
				+ expressNo);
		if (StringUtils.isNotEmpty(expressNo)
				&& StringUtils.isNotEmpty(orderno)) {
			try {
				List<WorkOrder> orders = this.workOrderService
						.reCheckOrderNoAndExpressNO(orderno, expressNo);
				if (null == orders || orders.isEmpty()) {
					json.put(Phone.J_KEY_STATUS,
							Phone.JsonStatus.ORD_RECHECK_FAILED);
					json.put(Phone.J_KEY_CONTENT, "操作失败：未查询到订单数据。");
					log.info("ajaxOrderRecheck query result is null.");
				} else if (1 == orders.size()) {
					log.debug("ajaxOrderRecheck query result is "
							+ orders.get(0));
					json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SUCCESS);
					json.put(Phone.J_KEY_CONTENT,
							Phone.JsonContent.ORD_RECHECK_SUCCESS);
				} else {
					log.info("ajaxOrderRecheck query result is list " + orders);
					json.put(Phone.J_KEY_STATUS,
							Phone.JsonStatus.ORD_RECHECK_ORDERS);
					json.put(Phone.J_KEY_CONTENT, "操作失败：查询有多个订单，请核对数据。");
				}
			} catch (Exception e) {
				// 此异常可不在此处捕获，最好由框架同意处理。
				log.error("ajaxOrderRecheck Exception", e);
				json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SERVER_ERR);
				json.put(Phone.J_KEY_STATUS, Phone.JsonContent.SERVER_ERR);
			}
		} else {
			if (!StringUtils.isNotEmpty(orderno)) {
				log.info("ajaxOrderRecheck order number is null.");
				json.put(Phone.J_KEY_STATUS,
						Phone.JsonStatus.ORD_RECHECK_ORDER_NO_NULL);
				json.put(Phone.J_KEY_CONTENT, "操作失败：订单编号为空，请核查。");
			} else if (!StringUtils.isNotEmpty(expressNo)) {
				log.info("ajaxOrderRecheck express number is null.");
				json.put(Phone.J_KEY_STATUS,
						Phone.JsonStatus.ORD_RECHECK_EXPRESS_NO_NULL);
				json.put(Phone.J_KEY_CONTENT, "操作失败：运单编号为空，请核查。");
			} else {
				log.info("ajaxOrderRecheck express number or order number is null.");
				json.put(Phone.J_KEY_STATUS,
						Phone.JsonStatus.ORD_RECHECK_PARAM_ERR);
				json.put(Phone.J_KEY_CONTENT, "操作失败：请求参数错误，请核查");
			}
		}
		writeJsonToResponse(json, response);
	}

	/**
	 * 托盘检查
	 * 
	 * @param lpnNO
	 * @param response
	 *            [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "ajaxPalletCheck")
	public void ajaxPalletCheck(@RequestParam(value = "lpnNo") String lpnNO,
			HttpServletResponse response) {
		JSONObject json = getInitJson();
		log.debug("ajaxPalletCheck Param lpnNO=" + lpnNO);
		if (StringUtils.isNotEmpty(lpnNO)) {
			try {
				Pallet pallet = palletService.getPalletByLpn(lpnNO);
				if (null != pallet) {
					if (StorageConstants.STATUS_FREE == pallet.getStatus()) {
						json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SUCCESS);
						json.put(Phone.J_KEY_CONTENT, "托盘为可用状态");
					} else {
						json.put(Phone.J_KEY_STATUS,
								Phone.JsonStatus.PALLET_NOT_FEE);
						json.put(Phone.J_KEY_CONTENT, "托盘不可用");
					}
					json.put("palletStatus", pallet.getStatus());
					json.put("palletLpn", pallet.getLpnNo());
					json.put("palletId", pallet.getId());
					json.put("warehouseCode", pallet.getWarehouseCode());
				} else {
					log.info("ajaxPalletCheck pallet not found.");
					json.put(Phone.J_KEY_STATUS,
							Phone.JsonStatus.PALLET_NOT_FOUND);
					json.put(Phone.J_KEY_CONTENT, "托盘不存在");
				}
			} catch (Exception e) {
				// 此异常可不在此处捕获，最好由框架統一处理。
				log.error("ajaxPalletCheck Exception", e);
				json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SERVER_ERR);
				json.put(Phone.J_KEY_CONTENT, Phone.JsonContent.SERVER_ERR);
			}
		} else {
			log.info("ajaxPalletCheck lpnNO is null.");
			json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.ORD_PALLET_LPN_NULL);
			json.put(Phone.J_KEY_CONTENT, "操作失败：请求参数错误");
		}
		writeJsonToResponse(json, response);
	}

	/**
	 * 检测订单是否可以装托盘
	 * 
	 * @param orderNo
	 * @param response
	 *            [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "ajaxPalletOrderCheck")
	public void ajaxPalletOrderCheck(
			@RequestParam(value = "orderNo") String orderNo,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletResponse response) {
		JSONObject json = getInitJson();
		log.debug("ajaxPalletOrder Param orderNo=" + orderNo
				+ ", warehouseCode = " + warehouseCode);
		if (StringUtils.isNotBlank(orderNo)
				&& StringUtils.isNotBlank(warehouseCode)) {
			try {
				WorkOrder workOrder = workOrderService
						.loadByAnyOrderno(orderNo);
				if (null != workOrder
						&& Constants.WorkerOrder.STATUS_SHIPPED
								.equals(workOrder.getStatus())) {
					if (!warehouseCode
							.trim()
							.toUpperCase()
							.equals(workOrder.getWarehouseCode().trim()
									.toUpperCase())) {
						json.put(Phone.J_KEY_STATUS,
								Phone.JsonStatus.PALLET_ORDER_NOT_TOGETHER);
						json.put(Phone.J_KEY_CONTENT, "订单与托盘非相同仓库");
					} else if (!storageOrderService.checkOrderIsBind(orderNo)) {
						json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SUCCESS);
						json.put(Phone.J_KEY_CONTENT, "订单可进行装箱操作。");
					} else {
						log.info("ajaxPalletOrder orderno is binding.");
						json.put(Phone.J_KEY_STATUS,
								Phone.JsonStatus.PALLET_ORDER_IS_BIND);
						json.put(Phone.J_KEY_CONTENT, "订单已为装箱状态，不能再次装箱。");
					}
				} else {
					log.info("ajaxPalletOrder orderno is binding.");
					json.put(Phone.J_KEY_STATUS,
							Phone.JsonStatus.PALLET_ORDER_NOT_SEND);
					json.put(Phone.J_KEY_CONTENT, "订单为非发货状态，不可进行装箱操作。");
				}
			} catch (Exception e) {
				// 此异常可不在此处捕获，最好由框架統一处理。
				log.error("ajaxPalletOrder Exception", e);
				json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SERVER_ERR);
				json.put(Phone.J_KEY_CONTENT, Phone.JsonContent.SERVER_ERR);
			}
		} else {
			log.info("ajaxPalletOrder lpnNO is null.");
			json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.ORD_PALLET_LPN_NULL);
			json.put(Phone.J_KEY_CONTENT, "操作失败：请求参数错误");
		}
		writeJsonToResponse(json, response);
	}

	/**
	 * 批量装托盘
	 * 
	 * @param lpnNo
	 * @param orderNos
	 * @param userId
	 * @param response
	 *            [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "loadedBatchPallet")
	public void loadedBatchPallet(@RequestParam(value = "lpnNo") String lpnNo,
			@RequestParam(value = "orderNos") String orderNos,
			@RequestParam(value = "userId") String userId,
			HttpServletResponse response) {
		JSONObject json = getInitJson();
		log.debug("loadedBatchPallet Param lpnNO=" + lpnNo);
		if (StringUtils.isNotEmpty(lpnNo) && StringUtils.isNotEmpty(orderNos)) {
			List<StorageOrder> list = palletService.checkPalletFeeByorderNo(orderNos);
			Pallet pallet = palletService.getPalletByLpn(lpnNo);
			if ((null != list && list.size() > 0)
					|| (null != pallet && StorageConstants.STATUS_FREE != pallet
							.getStatus())) {
				StringBuffer sb = new StringBuffer("") ;
            	for(StorageOrder s:list){
            		sb.append(s.getOrderNo()).append(",") ;
            	}
				json.put(Phone.J_KEY_STATUS,
						Phone.JsonStatus.PALLET_ORDER_IS_BIND);
				json.put(Phone.J_KEY_CONTENT, "托盘或订单已为装箱状态，不能再次装箱。"
						+ (null != list ? sb.toString().substring(0,sb.length()-1) : ""));
			} else {
				try {
					String[] orderArr = orderNos.split(",");
					List<StorageOrder> palletOrders = new ArrayList<StorageOrder>(
							orderArr.length);
					StorageOrder order = null;
					int batch = storageOrderService.getMaxBatchSeqByLpn(lpnNo) + 1;
					for (String num : orderArr) {
						order = new StorageOrder();
						order.setCreateTime(new Date());
						order.setBatchSeq(batch);
						order.setLpnNo(lpnNo);
						order.setStatus(StorageConstants.StorageOrder.STATUS_LOADED);
						order.setUpdateTime(new Date());
						order.setUserId(userId);
						order.setOrderNo(num);
						order.setIsValid(StorageConstants.VALID);
						palletOrders.add(order);
					}
					storageOrderService.loadedBatchPalletByLpn(lpnNo,
							palletOrders);
					json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SUCCESS);
					json.put(Phone.J_KEY_CONTENT, Phone.JsonContent.SUCCESS);
				} catch (Exception e) {
					// 此异常可不在此处捕获，最好由框架統一处理。
					log.error("loadedBatchPallet Exception", e);
					json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.SERVER_ERR);
					json.put(Phone.J_KEY_CONTENT, Phone.JsonContent.SERVER_ERR);
				}
			}
		} else {
			log.info("loadedBatchPallet lpnNo or orderNos is null.");
			json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.ORD_PALLET_LPN_NULL);
			json.put(Phone.J_KEY_CONTENT, "操作失败：请求参数错误，请核查");
		}
		writeJsonToResponse(json, response);
	}

	/**
	 * 新建并初始化json对象并返回
	 * 
	 * @return JSONObject [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 * @author zhangpeijun
	 */
	private JSONObject getInitJson() {
		JSONObject json = new JSONObject();
		json.put(Phone.J_KEY_STATUS, Phone.JsonStatus.DEFAULT);
		json.put(Phone.J_KEY_CONTENT, Phone.JsonContent.DEFAULT);
		return json;
	}

	/**
	 * 
	 * 将json对象写入响应流
	 * 
	 * @param json
	 * @param response
	 *            [参数说明]
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 * @author zhangpeijun
	 */
	private void writeJsonToResponse(JSONObject json,
			HttpServletResponse response) {
		if (null != response) {
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print(null != json ? json.toString() : "");
			} catch (IOException e) {
				log.error(null != json ? "Method param = " + json.toString()
						: "Method param json is null");
				log.error("Write json To response IOException", e);
			} finally {
				if (null != out) {
					out.close();
				}
			}
		}
	}
}
